<?php
namespace app\api\controller;

use app\api\logic\ExchangeOrderLogic;
use app\common\controller\RestController;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 兑换订单 exchangeOrder
 */
class ExchangeOrder extends RestController
{
    protected $noNeedLogin = [
        // 'orderDetail', 'orderExpress', 'changeAddress',
    ];

    /**
     * 订单预览
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function orderPreview(): bool
    {
        // 商品来源：1 日兮香商品 2 怡亚通商品
        $source        = input('source', '');
        $goodsInfo     = input('goodsInfo', '');
        $addressId     = input('addressId', 0);
        $exchange_type = input('exchangeType', 0);

        $info = ExchangeOrderLogic::getInstance()->orderPreview(
            $source,
            $exchange_type,
            $goodsInfo);

        // echo $this->result($info['rows'][0]['shopInfo']);exit;
        $info['tips'] = ExchangeOrderLogic::getInstance()->estimatedDelivery(
            $info['rows'][0]['shopInfo']['sendCity'] ?? '',
            $addressId,
        );
        return $this->result($info);
    }

    /**
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function createOrder(): bool
    {
        // 商品来源：1 日兮香商品 2 怡亚通商品
        $source    = input('source', 1);
        $goodsInfo = input('goodsInfo', '');
        $addressId = input('addressId', 0);
        $price     = input('price', 0);
        $amount    = input('amount', 0);
        $orderType = input('orderType', 1);
        $userNotes = input('userNote', '');

        $coin          = input('coin', -1);
        $exchange_type = input('exchangeType', 0);

        $info = ExchangeOrderLogic::getInstance()->createOrder(
            $goodsInfo,
            $addressId,
            $orderType,
            $price,
            $amount,
            $userNotes,
            [
                'coin'          => $coin,
                'source'        => $source,
                'exchange_type' => $exchange_type,
            ],
        );
        return $this->result($info);
    }

    public function orderDetail(): bool
    {
        $orderNo = input('orderNo', 0);
        $info    = ExchangeOrderLogic::getInstance()->orderDetail($orderNo);
        // 0待支付 1待发货 2待收货 3已收货 4已完成 5退款中 6退款成功 7取消 8超时取消 9待退货
        $status = $info['orderInfo']['status'];
        // $status = 1;
        if ($status == 1) {
            $tips     = ['仓库处理中 预计在2个工昨日内发货'];
            $createAt = $info['orderInfo']['createAt'];
            $date     = new \DateTime($createAt);
            $date->modify('+2 day');
            $diff = strtotime($createAt) + 172800;
            $now  = time();
            if ($now > $diff) {
                $tips[] = '1预计' . $date->format('n月j日') . '24:00前发货，' . ExchangeOrderLogic::getInstance()->estimatedDelivery(
                    $info['orderShop'][0]['shopId'] ?? '',
                    $info['orderAddress']['city'] ?? '',
                    $date,
                    3
                );
            } else {
                $tips[] = '预计' . $date->format('n月j日') . '24:00前发货，' . ExchangeOrderLogic::getInstance()->estimatedDelivery(
                    $info['orderShop'][0]['shopId'] ?? '',
                    $info['orderAddress']['city'] ?? '',
                    $date,
                    4
                );
            }
            $info['tips'] = $tips;
        } else if ($status == 2) {
            $goodsId = $info['orderShop'][0]['goodsInfo'][0]['goodsId'] ?? 0;
            // var_dump($goodsId);exit;
            $express = ExchangeOrderLogic::getInstance()->orderExpress(
                $orderNo,
                $goodsId);
            // echo json_encode($express, 320);exit;
            $info['tips'] = empty($express['expressList'][0]) ? [] : [
                $express['expressList'][0] ?? [],
            ];
            // $info['tips'] = [{"time":"2024-01-15 21:20:54","context":"已签收，签收人凭取货码签收。起早贪黑不停忙，如有不妥您见谅，好评激励我向上，求个五星暖心房。","ftime":"2024-01-15 21:20:54","areaCode":null,"areaName":null,"status":"签收"}]
        } else {
            $info['tips'] = [];
        }
        if (in_array($status, [5, 6])) {
            $userinfo = \think\App::getInstance()->userinfo;
            // idx_UserId_ExchangeOrdereNo_ExchangeOrderGoodsId
            $info['refundStatus'] = \think\facade\Db::table('order_refund')
                ->where('user_id', $userinfo->id)
                ->where('order_no', $orderNo)
                ->value('status');
            // $info['processes'] = ExchangeOrderRefundLogic::getInstance()->processe($info['refundStatus']);
        }
        return $this->result($info);
    }

    /**
     * 订单物流信息
     * @return [type] [description]
     */
    public function orderExpress(): bool
    {
        $orderNo = input('orderNo', 0);
        $goodsId = input('goodsId', 0);

        $info = ExchangeOrderLogic::getInstance()
            ->orderExpress($orderNo, $goodsId);
        return $this->result($info);
    }

    /**
     * 删除订单
     * @return bool
     */
    public function delOrder(): bool
    {
        $orderNo = input('orderNo', 0);
        $info    = ExchangeOrderLogic::getInstance()->delOrder($orderNo);
        return $this->result([]);
    }

    /**
     * 取消订单
     * @return [type] [description]
     */
    public function cancelOrder(): bool
    {
        $orderNo = input('orderNo', 0);
        $info    = ExchangeOrderLogic::getInstance()->cancelOrder($orderNo);
        return $this->result($info);
    }

    /**
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function orderList(): bool
    {
        $page      = input('page', 1);
        $pageSize  = input('pageSize', 10);
        $type      = input('type', 1);
        $orderType = input('orderType', 2);

        $info = ExchangeOrderLogic::getInstance()->orderList(
            $type,
            $orderType,
            $page,
            $pageSize);
        return $this->result($info);
    }

    /**
     * 兑换订单 确认收货
     * @return [type] [description]
     */
    public function taskOrder(): bool
    {
        $orderNo = input('orderNo', 0);

        $info = ExchangeOrderLogic::getInstance()
            ->taskOrder($orderNo);
        return $this->result($info);
    }

    /**
     * 订单滚动提醒消息
     *
     * @return [type] [description]
     */
    public function notice()
    {
        // $offset = random_int(0, 10);
        $offset = 0;
        $limit  = input('pageSize', 20);
        $items  = \think\facade\Db::table('exchange_order_goods')
            ->field(['DISTINCT m.user_name,og.goods_title'])
            ->alias('og')
            ->join('member m', 'og.user_id = m.id')
            ->order('og.id desc')
            ->limit($offset, $limit)
            ->select()->toArray();
        $debug = [];
        // $debug[] = \think\facade\Db::table('exchange_order_goods')
        //     ->getlastsql();
        $max = 5;
        // 检查数组元素的数量
        if (count($items) > $max) {
            // 数组元素大于$max，随机选取$max个元素
            $randomKeys = array_rand($items, $max);
            $items2     = [];
            foreach ($randomKeys as $key) {
                $items2[] = $items[$key];
            }
        } else {
            $items2 = $items;
        }
        $rows = [];
        foreach ($items2 as $item) {
            $rows[] = sprintf('会员 %s 兑换[%s] 兑换成功', $item['user_name'], $item['goods_title']);
        }
        return $this->result([
            'debug' => $debug,
            'rows'  => $rows,
        ]);
    }

    /**
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    //
    // public function payOrder(): bool
    // {
    //     $orderNo     = input('orderNo', '');
    //     $payType     = input('payType', 1);
    //     $payPassword = input('payPassword', 0);
    //     $paySubType  = input('paySubType', 0);

    //     $info = PayLogic::getInstance()->payOrder(
    //         $orderNo,
    //         $payType,
    //         $payPassword,
    //         $paySubType);
    //     return $this->result($info);
    // }
}
